/*****************************************************************************************[Main.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef __STDC_FORMAT_MACROS 
    #define __STDC_FORMAT_MACROS
#endif

#ifndef __STDC_LIMIT_MACROS 
    #define __STDC_LIMIT_MACROS
#endif



#include <errno.h>
#include <signal.h>
#include <sys/resource.h>

#include <zlib.h>
#include <netdb.h>
#include <pthread.h>
#include<time.h>

#include "../mtl/IntTypes.h"
#include "../utils/System.h"
#include "../utils/ParseUtils.h"
#include "../utils/Options.h"
#include "../core/Dimacs.h"
#include "../core/Solver.h"

#include "../core/parallel.h"

using namespace std;
using namespace Minisat;

void init_solver(Solver& s, double rand_seed);

bool parallel_data::Threads_Exit_flag;
pthread_mutex_t parallel_data::Threads_Exit_flag_mux;

void* parallel_data::global_trial;
pthread_mutex_t parallel_data::global_trial_mux;

//=================================================================================================

typedef struct
{
    pthread_t this_thread;
    int thread_index;
    int argc;
    int verbosity;
    StreamBuffer* inputfile;
    char** argv;
} thread_arg_type;

//______________________________________________

void printStats(Solver& solver)
{
    double cpu_time = cpuTime();
    double mem_used = memUsedPeak();
    printf("restarts              : %"PRIu64"\n", solver.starts);
    printf("conflicts             : %-12"PRIu64"   (%.0f /sec)\n", solver.conflicts   , solver.conflicts   /cpu_time);
    printf("decisions             : %-12"PRIu64"   (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions   /cpu_time);
    printf("propagations          : %-12"PRIu64"   (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time);
    printf("conflict literals     : %-12"PRIu64"   (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals);
    if (mem_used != 0) printf("Memory used           : %.2f MB\n", mem_used);
    printf("CPU time              : %g s\n", cpu_time);

}

static Solver* solver;
// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case
// for this feature of the Solver as it may take longer than an immediate call to '_exit()'.
static void SIGINT_interrupt(int signum) { solver->interrupt(); }

// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls
// destructors and may cause deadlocks if a malloc/free function happens to be running (these
// functions are guarded by locks for multithreaded use).
static void SIGINT_exit(int signum) {
    printf("\n"); printf("*** INTERRUPTED ***\n");
    if (solver->verbosity > 0){
        printStats(*solver);
        printf("\n"); printf("*** INTERRUPTED ***\n"); }
    _exit(1); }

void* Solve_thread_func(void* arg)
{
    thread_arg_type this_thread;
    this_thread = *(thread_arg_type*) arg;
    printf("Thread[%d] has been called\n",this_thread.thread_index);
    
    try{
            Solver S;
            
            S.Thread_id=abs(this_thread.this_thread);
            S.Thread_index=this_thread.thread_index;
            S.verbosity = this_thread.verbosity;

            solver = &S;
            gzFile in = gzopen(this_thread.argv[1], "rb");
            StreamBuffer inputs(in);
            parse_DIMACS_main (inputs, S);
            gzclose(in);


            //output file
            FILE* res = (this_thread.argc >= 3) ? fopen(this_thread.argv[2], "wb") : NULL;

            time_t stime;
            time(&stime);
            parallel_data::check_other_threads(S.Thread_index);
            if (!S.simplify()){
                parallel_data::check_other_threads(S.Thread_index);
                parallel_data::exit_thread(S.Thread_index);
                if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
                if (S.verbosity > 0){
                    printf("===============================================================================\n");
                    printf("Solved by unit propagation\n");
                    printStats(S);
                    printf("\n"); }
                printf("UNSATISFIABLE\n");
                printf("\n\n\nWinner: %d\n", this_thread.thread_index);
                exit(20);
            }

            vec<Lit> dummy;
            lbool ret = S.solveLimited(dummy);
            parallel_data::check_other_threads(S.Thread_index);
            parallel_data::exit_thread(S.Thread_index);

            if (S.verbosity > 0)
            {
                printStats(S);
                printf("\n"); 
            }

            printf(ret == l_True ? "SATISFIABLE\n" : ret == l_False ? "UNSATISFIABLE\n" : "INDETERMINATE\n");
            if (res != NULL)
            {
                if (ret == l_True){
                    fprintf(res, "SAT\n");
                    for (int i = 0; i < S.nVars(); i++)
                        if (S.model[i] != l_Undef)
                            fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
                    fprintf(res, " 0\n");
                }else if (ret == l_False)
                    fprintf(res, "UNSAT\n");
                else
                    fprintf(res, "INDET\n");
                fclose(res);
            }

            //End of thread
            time_t eTime;
            time(&eTime);
            double totaltime=difftime(eTime,stime);
            printf("\t\t\t\tTotal Time = %d sec\n",(int)totaltime);

    #ifdef NDEBUG
            exit(ret == l_True ? 10 : ret == l_False ? 20 : 0);     // (faster than "return", which will invoke the destructor for 'Solver')
    #else
            //return (void*)(ret == l_True ? 10 : ret == l_False ? 20 : 0);
    #endif



    }
catch (OutOfMemoryException&){
        printf("===============================================================================\n");
        printf("INDETERMINATE\n");
        exit(0);
    }
 return NULL;
}
//=================================================================================================
// Main:

int do_calculation()
{
    int x=0;
    while(1)
    {
        x=x*2;
        x=x/2;
        x+=1;
        x-=2;
        x+=1;

    }
    return 0;
}
void* thread_test (void* arg)
{
    do_calculation();
    return NULL;
}
int main(int argc, char** argv)
{

    // Set proirity value
    int nice= setpriority(PRIO_PROCESS,0,-20);

    setUsageHelp("USAGE: %s [options] <input-file> <result-output-file>\n\n  where input may be either in plain or gzipped DIMACS.\n");
     printf("This is MiniSat 2.2 beta\n");

    #if defined(__linux__)
        int numCPU = sysconf( _SC_NPROCESSORS_ONLN );
        printf("This system has %d cores\n",numCPU);
        fpu_control_t oldcw, newcw;
        _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
        printf("WARNING: for repeatability, setting FPU to use double precision\n");
    #endif

        // Extra options:
        //
        IntOption    verb   ("MAIN", "verb",   "Verbosity level (0=silent, 1=some, 2=more).", 1, IntRange(0, 2));
        IntOption    cpu_lim("MAIN", "cpu-lim","Limit on CPU time allowed in seconds.\n", INT32_MAX, IntRange(0, INT32_MAX));
        IntOption    mem_lim("MAIN", "mem-lim","Limit on memory usage in megabytes.\n", INT32_MAX, IntRange(0, INT32_MAX));


        parseOptions(argc, argv, true);

        // Use signal handlers that forcibly quit until the solver will be able to respond to
        // interrupts:
        signal(SIGINT, SIGINT_exit);
        signal(SIGXCPU,SIGINT_exit);

        //init_solver(S,101);

        // Set limit on CPU-time:
        if (cpu_lim != INT32_MAX){
            rlimit rl;
            getrlimit(RLIMIT_CPU, &rl);
            if (rl.rlim_max == RLIM_INFINITY || (rlim_t)cpu_lim < rl.rlim_max){
                rl.rlim_cur = cpu_lim;
                if (setrlimit(RLIMIT_CPU, &rl) == -1)
                    printf("WARNING! Could not set resource limit: CPU-time.\n");
            } }

        // Set limit on virtual memory:
        if (mem_lim != INT32_MAX){
            rlim_t new_mem_lim = (rlim_t)mem_lim * 1024*1024;
            rlimit rl;
            getrlimit(RLIMIT_AS, &rl);
            if (rl.rlim_max == RLIM_INFINITY || new_mem_lim < rl.rlim_max){
                rl.rlim_cur = new_mem_lim;
                if (setrlimit(RLIMIT_AS, &rl) == -1)
                    printf("WARNING! Could not set resource limit: Virtual memory.\n");
            } }

        if (argc == 1)
            printf("Reading from standard input... Use '--help' for help.\n");

        gzFile in = (argc == 1) ? gzopen(0, "rb") : gzopen(argv[1], "rb");

        if (in == NULL)
            printf("ERROR! Could not open file: %s\n",argc == 1 ? "<stdin>" : argv[1]), exit(1);

        if (verb > 0){
            printf("============================[ Problem Statistics ]=============================\n");
            printf("|                                                                             |\n"); }

        StreamBuffer inputfile(in);

        double initial_time = cpuTime();
        Solver* dumy= new Solver();
        parse_DIMACS_main (inputfile, *dumy);
        
        if (verb > 0){
            printf("|  Number of variables:  %12d                                         |\n", dumy->nVars());
            printf("|  Number of clauses:    %12d                                         |\n", dumy->nClauses()); }

        double parsed_time = cpuTime();
        if (verb > 0){
            printf("|  Parse time:           %12.2f s                                       |\n", parsed_time - initial_time);
            printf("|                                                                             |\n"); }

        delete dumy;
        
        // Change to signal-handlers that will only notify the solver and allow it to terminate
        // voluntarily:
        signal(SIGINT, SIGINT_interrupt);
        signal(SIGXCPU,SIGINT_interrupt);
//************************************************************


       int Res;
        thread_arg_type threads[numCPU];
        cpu_set_t cpu_Sets[numCPU];
        parallel_data::init_members(5);

        for(int i=0;i<numCPU;i++)
        {

            threads[i].argc = argc;
            threads[i].argv=  argv;
            threads[i].thread_index=i;
            threads[i].verbosity=verb;
            threads[i].inputfile = &inputfile;
            
            
        }
       

        
        
        for(int i=0;i<numCPU;i++)
        //for(int i=0;i<1;i++)
        {
            CPU_ZERO(&cpu_Sets[i]);
            CPU_SET(i,&cpu_Sets[i]);

            Res=pthread_create(&threads[i].this_thread,NULL,Solve_thread_func,(void*) &threads[i]);
            if(Res==0)
                printf("thread[%d] has been created\n",threads[i].thread_index);
            Res = pthread_setaffinity_np(threads[i].this_thread,sizeof(cpu_set_t),&cpu_Sets[i]);
        }
        Res = pthread_setaffinity_np(pthread_self(),sizeof(cpu_set_t),&cpu_Sets[0]);

        for(int i=0;i<numCPU;i++)
        {
            pthread_join(threads[i].this_thread,NULL);
            printf("Thread[%d] is back\n",threads[i].thread_index);
        }
        
        
        if(nice!=0)
            printf("to get better performance run this program with root user\n");



}
